using MediatR;
using MeetingManagement.Domain.Entities;
using MeetingManagement.Domain.Repositories;

namespace MeetingManagement.Application.Commands.Users.Login
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, LoginResult>
    {
        private readonly IRepository<User> _userRepository;
        private readonly Application.Common.IJwtTokenService _jwtTokenService;
        private readonly Application.Common.IPasswordHasher _passwordHasher;
        public LoginCommandHandler(
            IRepository<User> userRepository,
            Application.Common.IJwtTokenService jwtTokenService,
            Application.Common.IPasswordHasher passwordHasher)
        {
            _userRepository = userRepository;
            _jwtTokenService = jwtTokenService;
            _passwordHasher = passwordHasher;
        }

        public Task<LoginResult> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(request.Email) || string.IsNullOrWhiteSpace(request.Password))
            {
                return Task.FromResult(new LoginResult { Success = false, Message = "邮箱和密码不能为空" });
            }

            var user = _userRepository.Query().FirstOrDefault(u => u.Email == request.Email);
            if (user == null) return Task.FromResult(new LoginResult { Success = false, Message = "用户不存在" });



            if (!_passwordHasher.Verify(user.PasswordHash, request.Password)) return Task.FromResult(new LoginResult { Success = false, Message = "密码错误" });

            user.RecordLogin();

            var token = _jwtTokenService.GenerateToken(user.Id.ToString(), user.Username, user.Email, user.Role);

            return Task.FromResult(new LoginResult
            {
                Success = true,
                Message = "登录成功",
                UserName = user.Username,
                Email = user.Email,
                Token = token
            });
        }
    }
}
